package zhongbo.java.air.airmonitor.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.airmonitor.config.RedisListenerConfig;
import zhongbo.java.air.airmonitor.model.AirAlertLog;
import zhongbo.java.air.airmonitor.model.dto.PointDto;
import zhongbo.java.air.airmonitor.service.IAirAlertLogService;
import zhongbo.java.air.airmonitor.service.IJtsService;
import zhongbo.java.air.airmonitor.web.websocket.AlertZoneWebSocket;
import zhongbo.java.air.airmonitor.web.websocket.LiveWebSocket;
import zhongbo.java.air.dictionary.model.AirAlertZone;
import zhongbo.java.air.dictionary.service.IAirAlertZoneService;

import javax.websocket.Session;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisLogSubscribeLogChanelListener implements MessageListener {

    @Autowired
    private RedisLogChanelPublisher redisLogChanelPublisher;

    @Autowired
    private IAirAlertZoneService<AirAlertZone> airAlertZoneService;

    @Autowired
    private IAirAlertLogService<AirAlertLog> airAlertLogService;

    @Autowired
    private IJtsService jtsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = new String(message.getChannel()); // 获取频道名称
        String rawMsg = new String(message.getBody());
        log.info("接收到频道 [{}] Json航迹数据: {}", channel, rawMsg);
        rawMsg = rawMsg.replace("\\", "");
        rawMsg = rawMsg.substring(1, rawMsg.length() - 1);
        LiveWebSocket.sendMessage(rawMsg);

        JSONObject jsonObject = JSONUtil.parseObj(rawMsg);
        String redisKey = " alert:history:zhu:" + jsonObject.getStr("icaoCode");
        List<AirAlertZone> airAlertZoneList = airAlertZoneService.queryAll();
        if (airAlertZoneList != null){
//            AirAlertLog airAlertLog = airAlertLogService.queryByIcaoCodeAndTriggerTime(jsonObject.getStr("icaoCode"), jsonObject.getDate("timestamp"));
            String s = stringRedisTemplate.opsForValue().get(redisKey);
            if (s == null || s.isEmpty()){
                AirAlertLog addAirAlertLog = null;
                for (AirAlertZone airAlertZone : airAlertZoneList){
                    List<PointDto> pointDtos = jtsService.parseAlertZoneVertices(airAlertZone.getVertices());
                    boolean inAlertZone = jtsService.isInAlertZone(pointDtos, jsonObject.getDouble("longitude"), jsonObject.getDouble("latitude"));
                    if (inAlertZone){
                        String triggerCoordinates = "{\"lon\":" + jsonObject.getDouble("longitude") + ",\"lat\":" + jsonObject.getDouble("latitude") + "}";
                        addAirAlertLog = new AirAlertLog(airAlertZone.getId(),
                                airAlertZone.getZoneCode(),
                                jsonObject.getStr("icaoCode"),
                                airAlertZone.getZoneType(),
                                triggerCoordinates,
                                jsonObject.getDate("timestamp"),
                                "未处理",
                                new Date(), new Date());
                        airAlertLogService.insert(addAirAlertLog);
                        String msg = JSONUtil.toJsonStr(addAirAlertLog);
                        stringRedisTemplate.opsForValue().set(redisKey, msg,5, TimeUnit.MINUTES);
                        log.info("已储存 {} 到redis服务器，对应数据 ->>> {}", redisKey,msg);
                        AlertZoneWebSocket.sendMessage(msg);
                    }
                }
            }
        }
    }
}